import { request } from '@umijs/max';
import { message } from 'antd';

export const registerEvent = (
  getSubmitUrl: (param: any) => string,
  submitMethod: string,
  getData?: () => any | undefined,
  loadingSetter?: (loading: boolean) => void,
): void => {
  window.addEventListener('message', (event: MessageEvent<any>) => {
    const eventData = event.data;
    const params = eventData.params;
    switch (eventData.cmd) {
      case 'submitted':
        return request(
          getSubmitUrl(params),
          {
            method: submitMethod,
            data: getData?.(),
          },
        ).then(() => {
          message.success('提交流程成功');
          window.setTimeout(() => {
            window.close();
          }, 1000);
        }).catch((err) => {
          message.error('提交表单异常');
          console.log('表单提交异常:' + err);
          loadingSetter?.(false);
        });
        break;
      case 'heightChanged':
        document.getElementById('form-content')!.style.height =
          params.height + 'px';
        break;
      case 'error':
        message.error('处理数据错误');
        loadingSetter?.(false);
        break;
    }
  });
};
